<?php
namespace JsonLowCode\Form\Fields;

use Closure;
use JsonLowCode\Form;;
use JsonLowCode\Support\Js;

/**
 * 键值对数组
 */
class ObjectListField extends DynamicInputField
{
    protected function booted(): void
    {
        parent::booted();
        $this->preset('pair');
        $this->object(function (Form\Make $make){
            $make->groupLabel("键");
            $make->text("key")->placeholder("请输入键");
            $make->groupLabel("值");
            $make->text("value")->placeholder("请输入值");
        });
    }

    public function object(Closure $children, string $bindName = "params"): static
    {
        $bindIndex = Js::this("{$bindName}.index");
        $form = Form::make(null,function (Form $form){
            $form->setNoItem();
            $form->setMode("make");
            $form->form()->labelWidth("100");
        });
        $form->setBindKey("{$bindName}.value");
        $form->group()->item(function (Form\Make $make) use ($children, $bindIndex) {
            $make->setNoItem();
            call_user_func($children,$make,$bindIndex);
        });
        $data = $form->setData();
        $params = json_encode($data,JSON_UNESCAPED_UNICODE);
        $this->element->onCreate(Js::func("return {$params};"));
        $this->element->slotDefault($form->elements(), [$bindName]);
        return $this;
    }


    /**
     * 键输入框提示
     * @param string $placeholder
     * @return $this
     */
    public function keyPlaceholder(string $placeholder): static
    {
        $this->element->keyPlaceholder($placeholder);
        return $this;
    }

    /**
     * 值输入框提示
     * @param string $placeholder
     * @return $this
     */
    public function valuePlaceholder(string $placeholder): static
    {
        $this->element->valuePlaceholder($placeholder);
        return $this;
    }
}
